<?php

namespace Lib\Db;

class Redis extends \Home {

    private static $key = 'default';

    private static $redis = array();

    /**
     * @param string $key
     * @return \Redis
     */
    public static function instance($key = 'default') {
        self::$key = $key;
        return parent::instance();
    }

    public function connect($key = null) {
        if (!$key) {
            $key = self::$key;
        }

        if (empty(self::$redis[$key])) {
            $configName = \Main::$appNamespace . 'Config\Redis';
            $config = (array) new $configName();
            if (empty($config[$key])) {
                $this->throwException('The miss a configuration item.');
            }
            $config = $config[$key];
            $mustKey = array('host', 'port', 'db');
            foreach ($mustKey as $v) {
                if (!isset($config[$v])) {
                    $this->throwException($v . ' must be configured.');
                }
            }
            $redis = new \Redis();
            $redis->connect($config['host'], $config['port']);
            $redis->select($config['db']);
            self::$redis[$key] = $redis;
        }
        return self::$redis[$key];
    }

    public function __call($func, $p) {
        $redis = $this->connect();
        return call_user_func_array(array($redis, $func), $p);
    }

    private function throwException($msg, $code = 0, $previous = null) {
        throw new \Lib\Exception\Db($msg, $code, $previous);
    }

}